//
//  LRNetwork.m
//  LRShop
//
//  Created by HCW on 16/7/28.
//  Copyright © 2016年 HCW. All rights reserved.
//

#import "LRNetwork.h"

@implementation LRNetwork

#pragma mark - 监测网络的可链接性
/*
+ (void)netWorkReachabilityWithURLString:(NSString *)strUrl resultBlock:(NetWorkBlock)netWorkBlock
{
    NSURL *baseURL = [NSURL URLWithString:strUrl];
    
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
    
    NSOperationQueue *operationQueue = manager.operationQueue;
    
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];
                if (netWorkBlock) netWorkBlock(YES);
                break;
            case AFNetworkReachabilityStatusNotReachable:
                if (netWorkBlock) netWorkBlock(NO);
            default:
                [operationQueue setSuspended:YES];
                break;
        }
    }];
    
    [manager.reachabilityManager startMonitoring];
}
 */

#pragma mark - GET

+ (void) netRequestGETWithRequestURL: (NSString *) requestURLString
                       withParameter: (NSDictionary *) parameter
                withReturnValeuBlock: (ReturnValueBlock) block
                  withErrorCodeBlock: (ErrorCodeBlock) errorBlock
                    withFailureBlock: (FailureBlock) failureBlock
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 60;
    [session.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
    [session GET:requestURLString parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject) {
        
        DLog(@"%@", responseObject);
        NSNumber *code = responseObject[@"success"];
        if ([code isEqualToNumber:@(1)]) {
            if (block) block(responseObject);
        } else {
            if (errorBlock) errorBlock([code integerValue] ,responseObject[@"reason"]);
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (failureBlock) failureBlock();
    }];
}

#pragma mark - POST

+ (void) netRequestPOSTWithRequestURL: (NSString *) requestURLString
                        withParameter: (NSDictionary *) parameter
                 withReturnValeuBlock: (ReturnValueBlock) block
                   withErrorCodeBlock: (ErrorCodeBlock) errorBlock
                     withFailureBlock: (FailureBlock) failureBlock
{
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 60;
    [session.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];

    [session POST:requestURLString parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject) {
        
        //解密

//        NSDictionary * dict = [self dictionaryWithJsonString:responseObject];
        NSDictionary * dict = responseObject;
//         NSLog(@"%@",responseObject);
        NSString *code = dict[@"flag"];  // status为20000是正确数据，其他为异常数据
        if ([code isEqualToString:@"1"]) {
           
            if (block) block(dict[@"data"]);
            
        } else {
            if ([code isEqualToString:@"-6"]){
                [USER_DEFAULTS removeObjectForKey:@"user_id"];
                [USER_DEFAULTS removeObjectForKey:@"verify"];
                [USER_DEFAULTS removeObjectForKey:@"allConstProjectid"];
                [USER_DEFAULTS removeObjectForKey:@"projArr"];
                [USER_DEFAULTS removeObjectForKey:@"activity_id"];
                [USER_DEFAULTS synchronize];
                allConstMemberid = nil;
                allConstMD5id = nil;
                allConstProjectid = nil;
                UINavigationController *nvc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateInitialViewController];
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nvc animated:YES completion:^{}];
                [[[UIAlertView alloc] initWithTitle:@"下线通知" message:@"您的帐号在别的设备上登录，您被迫下线！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
            }
            if (errorBlock) errorBlock([code integerValue] ,dict[@"msg"]);
            
        }

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (failureBlock) failureBlock();
        NSLog(@"%@",error);
    }];
    
}

#pragma mark - POST IMAGES

+ (void) netRequestPOSTImagesWithRequestURL: (NSString *) requestURLString
                              withParameter: (NSDictionary *) parameter
                               withFileData: (NSArray *) images
                       withReturnValeuBlock: (ReturnValueBlock) block
                         withErrorCodeBlock: (ErrorCodeBlock) errorBlock
                           withFailureBlock: (FailureBlock) failureBlock
                    withUploadProgressBlock: (UploadProgressBlock) uploadProgressBlock
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer =  [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = 60;
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil];
    [session POST:requestURLString parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (images.count>0) {
            
            for (int i=0; i<images.count; i++) {
                
                //时间戳命名
                NSTimeInterval time = [NSDate date].timeIntervalSince1970 * 1000;
                NSString *name = [NSString stringWithFormat:@"%f%d.jpg",time, i];
                
                NSData *imageData = UIImageJPEGRepresentation(images[i], 0.6);
                if (i == 0) {
                     [formData appendPartWithFileData:imageData name:@"id_card_front" fileName:name mimeType:@"image/jpeg"];
                }else if (i == 1){
                    [formData appendPartWithFileData:imageData name:@"id_card_back" fileName:name mimeType:@"image/jpeg"];
                }
            }
        }
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        DLog(@"%@", dic);
        //解密

//        NSDictionary * dict = [self dictionaryWithJsonString:responseObject];
        NSString *code = dic[@"flag"];  // status为20000是正确数据，其他为异常数据
        if ([code isEqualToString:@"1"]) {
            [HUD showSucceedMsg:dic[@"msg"]];
            if (block) block(dic[@"data"]);
        } else {
            
            if (errorBlock) errorBlock([code integerValue] ,dic[@"msg"]);
            [HUD showErrorMsg:dic[@"msg"]];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (failureBlock) failureBlock();
    }];
    
}
-(NSString *)removeUnescapedCharacter:(NSString *)inputStr
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];//获取那些特殊字符
    NSRange range = [inputStr rangeOfCharacterFromSet:controlChars];//寻找字符串中有没有这些特殊字符
    if (range.location != NSNotFound)
    {
        NSMutableString *mutable = [NSMutableString stringWithString:inputStr];
        while (range.location != NSNotFound)
        {
            [mutable deleteCharactersInRange:range];//去掉这些特殊字符
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputStr;
}


@end
